import json
import requests
from Crypto.Cipher import DES
from Crypto.Util.Padding import pad, unpad
from abc import ABC, abstractmethod
from config import Config

config = Config()


class CryptoStrategy(ABC):
    """加密策略抽象基类"""

    @abstractmethod
    def encrypt(self, plaintext: str) -> bytes:
        pass

    @abstractmethod
    def decrypt(self, ciphertext: bytes) -> str:
        pass


class DESStrategy(CryptoStrategy):
    """DES加密策略实现"""

    def __init__(self, key: str):
        self.key = self._process_key(key)

    def _process_key(self, key: str) -> bytes:
        """处理密钥格式"""
        key_bytes = key.encode("utf-8")
        return pad(key_bytes, 8)[:8]  # 确保密钥长度为8字节

    def encrypt(self, plaintext: str) -> bytes:
        cipher = DES.new(self.key, DES.MODE_ECB)
        return cipher.encrypt(pad(plaintext.encode("utf-8"), 8))

    def decrypt(self, ciphertext: bytes) -> str:
        cipher = DES.new(self.key, DES.MODE_ECB)
        return unpad(cipher.decrypt(ciphertext), 8).decode("utf-8")


class APIClient:
    """通用API客户端（支持多态加密策略）"""

    def __init__(self, crypto: CryptoStrategy):
        self.crypto = crypto
        self.headers = {"Content-Type": "application/json;charset=UTF-8"}

    def send_request(self, url: str, data: dict) -> bytes:
        """发送加密请求的通用方法"""
        encrypted_data = self.crypto.encrypt(json.dumps(data))
        response = requests.post(url, headers=self.headers, data=encrypted_data)
        response.raise_for_status()
        return response.content


class TaskAPIClient(APIClient):
    """任务专用API客户端"""

    def send_task_data(self, data: dict) -> bytes:
        return self.send_request(
            "https://d-k8s-ws-fp.bigfintax.com/taskDataReceived", data
        )


if __name__ == "__main__":
    des_crypto = DESStrategy(config.KEY)
    api_client = TaskAPIClient(des_crypto)
    task_data = {
        "callback_request_id": "5216aee9-c04e-4381-9473-fbc5a2aa51f2",
        "data": {
            "taskSet": {
                "task": {
                    "tableSet": [
                        {
                            "result": {
                                "images": {
                                    "image": [
                                        "/ysb/image/202504/91120116MA05XWM76R/TaskLogin/20250402095158_498628.png",
                                        "/ysb/image/202504/91120116MA05XWM76R/TaskLogin/20250402095207_138632.png",
                                    ]
                                },
                                "code": "200C000000",
                                "desc": "【税局接口提示】新版登陆成功",
                            },
                            "param": {
                                "input": [
                                    {"id": "LoginName", "value": "15624833493"},
                                    {"id": "LoginPassword", "value": "fssc1111"},
                                    {"id": "LoginType", "value": "06"},
                                    {"id": "VpdnName"},
                                    {"id": "VpdnPassword"},
                                    {"id": "MobileCode", "value": "15624833493"},
                                    {"id": "sjhly", "value": "1"},
                                    {"id": "CrossRegionCity"},
                                    {"id": "CrossRegionDistrict"},
                                    {
                                        "id": "CrossRegionZgsj",
                                        "value": "国家税务总局天津经济技术开发区税务局黄海路税务所",
                                    },
                                    {
                                        "id": "ProductionAddress",
                                        "value": "南海路12号A3栋708室(天津亿企奋斗商务秘书有限公司托管第054号)",
                                    },
                                    {"id": "CAPassWord"},
                                    {"id": "zgsj", "value": ""},
                                    {"id": "kzzt"},
                                    {"id": "LoginSerialNumber"},
                                    {"id": "SbPhoneNum", "value": "15624833493"},
                                    {"id": "DataSource"},
                                    {"id": "ReLoginType", "value": "03"},
                                    {"id": "GroupName", "value": ""},
                                    {"id": "OrgTaxNum", "value": "91120116MA05XWM76R"},
                                    {
                                        "id": "CompanyName",
                                        "value": "天津小屋信息科技有限公司",
                                    },
                                    {"id": "QyxxPassword"},
                                    {"id": "AdministrativeDivision"},
                                    {
                                        "id": "LoginNsrsbh",
                                        "value": "91120116MA05XWM76R",
                                    },
                                    {"id": "Nsrsf", "value": "增值税一般纳税人"},
                                    {"id": "LegalRepresentative"},
                                    {"id": "RegisterCode"},
                                    {"id": "BusinessAddress", "value": ""},
                                    {"id": "Idcard"},
                                    {"id": "IdentInfo", "value": "办税人"},
                                    {"id": "IdentName", "value": "宋晨阳"},
                                    {"id": "AreaCode", "value": "12"},
                                    {"id": "IdentPhone", "value": "15624833493"},
                                    {"id": "IdentType", "value": "居民身份证"},
                                    {
                                        "id": "IdentNumber",
                                        "value": "130582200009290081",
                                    },
                                    {"id": "IdentPassword", "value": "fssc1111"},
                                    {"id": "PersonalTaxUsername"},
                                    {"id": "PersonalTaxPassword"},
                                    {"id": "TaxIdentity", "value": ""},
                                    {"id": "Dqdeh", "value": "0"},
                                    {"id": "platformNo", "value": "1000000198"},
                                    {"id": "nsrbm", "value": "91120116MA05XWM76R"},
                                    {"id": "UnionFundsName", "value": ""},
                                    {"id": "UnionFundsPhone", "value": ""},
                                    {"id": "UnionFundsPassword", "value": ""},
                                    {"id": "CrossRegionLogin", "value": "N"},
                                    {"id": "CrossRegionLoginOrgTaxNum"},
                                    {"id": "CrossRegionLoginAreaCode"},
                                    {"id": "SpecificSubject", "value": ""},
                                    {"id": "CrossRegionTaxManageNum", "value": ""},
                                ]
                            },
                            "id": "TaskLogin",
                        },
                        {
                            "result": {
                                "images": {
                                    "image": [
                                        "/ysb/image/202504/91120116MA05XWM76R/300109/20250402095213_776837.png"
                                    ]
                                },
                                "code": "200C000000",
                                "fileDownLoadUrl": "/ysb/swdacj/9131011366077364XA/2022-03/SWDACJ-SBB_700200_2022-03_9131011366077364XA.zip",
                                "desc": "【税局接口提示】执行任务成功！",
                            },
                            "taxStationDeclare": "1",
                            "ssqs": "2024-01-01",
                            "declareNumber": "1083273322512084992",
                            "id": "300109",
                            "sbrq": "2024-04",
                            "totalCount": "1",
                            "type": "SWDACJ-SBB",
                            "downloadCount": "1",
                            "ssqz": "2024-03-31",
                        },
                    ],
                    "id": "1200301",
                },
                "companyInfo": {
                    "creditCode": "91120116MA05XWM76R",
                    "companyName": "天津小屋信息科技有限公司",
                    "currentTaxNo": "",
                    "taxCode": "91120116MA05XWM76R",
                    "currentOrgName": "",
                    "taxpayerId": "91120116MA05XWM76R",
                },
            }
        },
        "serialnumber": "1083273322512084992",
        "env": "pro",
        "message": "【税局接口提示】执行任务成功！",
        "taskSource": "center",
        "type": "SWDACJ-SBB",
        "taskRequestId": "1067227669955346432",
        "track_md5": "5d731c85b63c4d4b87dbb7748781a280",
        "login_request_id": "e3529cd9-0f64-11f0-8a4c-525400877deb",
        "scf_name": "sfcj_5100301",
        "callbackurl": "https://ws-fp.bigfintax.com/taskDataReceived",
        "scf_start_time": 1743558715836,
        "request_id": "0e83c06c-0f65-11f0-9000-52540087a506",
        "ca": {
            "dport": "",
            "creditcode": "91120116MA05XWM76R",
            "cport": "",
            "companyname": "天津小屋信息科技有限公司",
            "ip": "",
            "vidpid": "",
            "taxcode": "91120116MA05XWM76R",
            "usbport": "",
            "taxpayerid": "91120116MA05XWM76R",
        },
        "status": "200C000000",
    }  # 替换实际任务数据
    task_response = api_client.send_task_data(task_data)
    res = des_crypto.decrypt(task_response)
    print(res)
